package com.fundamental.client;

import com.fundamental.server.NIOServer;
import com.fundamental.server.ServerConfig;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

public class NIOClient {



    private static NIOClient INSTANCE = new NIOClient();

    private ClientConfig config;

    private Selector selector;

    SocketChannel channel;

    private int state = -1;

    private AtomicInteger num = new AtomicInteger(0);

    public class WriteProcess implements Runnable{

        int retryTimes = 3;

        @Override
        public void run() {
            while (retryTimes > 0){
                try {
                    byte[] bytes = "time".getBytes();
                    //String str = new String(bytes);

                    System.out.println("发送时间"+System.nanoTime());

                    channel.write(ByteBuffer.wrap(bytes));
                    Thread.sleep(2000);
                } catch (Exception e) {
                    e.printStackTrace();
                    retryTimes --;
                }

            }
        }
    }

    //服务器暂定为单线程
    private void connect() throws IOException {
        try {
            channel = SocketChannel.open();
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_CONNECT);
            channel.connect(new InetSocketAddress(config.getAddress(), config.getPort()));

        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }


        //已经开始的服务器，不让他中断
        while (true) {
            try {
                selector.select();

                Set<SelectionKey> keySet = selector.selectedKeys();
                for(SelectionKey key : keySet){
                    if(key.isConnectable()){
                        SocketChannel channel = (SocketChannel) key.channel();
                        channel.finishConnect();
                        channel.register(selector,SelectionKey.OP_READ);
                        new Thread(new WriteProcess()).start();
                    }else if(key.isReadable()){
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        channel.read(buffer);
                        byte[] bytes = buffer.array();
                        String str = new String(bytes);
                        System.out.println("接收到字符串"+str+"于"+System.nanoTime());

                    }
                }

            }catch(Exception e){
                e.printStackTrace();
                System.out.println("连接出错");
                break;
            }
        }
    }


    public static void buildAndConnect(ClientConfig clientConfig){

        try {
            INSTANCE.config = clientConfig;
            INSTANCE.selector = Selector.open();
            INSTANCE.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }





}
